package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.MatRepairDeteMapper;
import com.indusfo.spc.mapper.MatRepairFlowMapper;
import com.indusfo.spc.mapper.MatRepairMapper;
import com.indusfo.spc.pojo.MatRepair;
import com.indusfo.spc.pojo.MatRepairDete;
import com.indusfo.spc.pojo.MatRepairFlow;
import com.indusfo.spc.service.MatRepairService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Author liub
 * @Date 2019/11/25 8:39
 * @Version 1.0
 */

@Service
public class MatRepairServiceImpl implements MatRepairService {

    /**
     * 声明日志的静态变量
     */
    private static final Logger logger = LoggerFactory.getLogger(MatRepairServiceImpl.class);

    @Resource
    private MatRepairMapper matRepairMapper;
    @Resource
    private MatRepairFlowMapper matRepairFlowMapper;
    @Resource
    private MatRepairDeteMapper matRepairDeteMapper;


    /**
     * 查询
     */
    @Override
    public JSONObject queryMatRepair(MatRepair matRepair) {
        try {
            if (matRepair.getMatVerId() == null) {
                throw new ModifyFailedException(HintMessage.MATVERID_NULL);
            }
            //获取页面的数据个数
            Integer pagesize = matRepair.getPagesize();
            //获取查询的页数
            Integer pageindex = matRepair.getPageindex();
            if (pagesize != null && pageindex != null) {
                matRepair.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<MatRepair> matRepairList = matRepairMapper.queryMatRepair(matRepair);

            //如果页数和页面数量都不为空的情况下进行计数
            if (matRepairList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, matRepairList, 0);
            } else {
                Integer count = matRepairMapper.countMatRepair(matRepair);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, matRepairList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }

    /**
     * 新增
     */
    @Override
    public JSONObject insertMatRepair(MatRepair matRepair) {
        try {
            if (matRepair.getMatRepairId() != null) {
                throw new ModifyFailedException(HintMessage.INSERT_ID);
            }
            //初始化基础数据
            if (matRepair.getDataState() == null) {
                matRepair.setDataState(1);
            }
            //判重
            checkParam(matRepair);
            //执行新增操作
            Integer row = matRepairMapper.insertMatRepair(matRepair);
            if (row == 0) {
                throw new ModifyFailedException(HintMessage.INSERT_DEFEATED);
            }
            return JSONObject.oK(HintMessage.INSERT_SUCCESS);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }

    }

    /**
     * 修改
     */
    @Override
    public JSONObject updateMatRepair(MatRepair matRepair) {
        try {
            if (matRepair.getMatRepairId() == null) {
                throw new ParamsErrorException(HintMessage.UPDATE_ID);
            }
            //初始化基础数据
            if (matRepair.getDataState() == null) {
                matRepair.setDataState(1);
            }
            //判重
            checkParam(matRepair);
            //执行修改操作
            int row = matRepairMapper.updateMatRepair(matRepair);
            if (row == 0) {
                throw new ModifyFailedException(HintMessage.UPDATE_DEFEATED);
            }
            return JSONObject.oK(HintMessage.UPDATE_SUCCESS);
        } catch (GlobalException e) {//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 删除
     */
    @Override
    public JSONObject deleteMatRepair(List<Integer> matRepairIds, Integer dataState) {
        try {
            //空值判断
            if (dataState == null) {
                throw new ParamsErrorException(HintMessage.DATASTATE_NULL);
            }
            if (matRepairIds == null) {
                throw new ParamsErrorException(HintMessage.LIST_NULL);
            }
            //记录异常信息
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = HintMessage.START_VALUE;
                    break;
                case 2:
                    msg = HintMessage.DELETE_VALUE;
                    break;
                case 3:
                    msg = HintMessage.STOP_VALUE;
                    break;
                default:
                    throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);
            }
            //执行删除操作
            int row = matRepairMapper.deleteMatRepair(matRepairIds, dataState);
            //声明msg字符串，用来存抛出的异常
            if (row == 0) {
                msg = msg + HintMessage.DEFEATED_VALUE;
            } else {
                msg = msg + HintMessage.SUCCESS_VALUE;
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 级联删除维修流程关联的工序、维修采集参数
     */
    @Transactional
    @Override
    public JSONObject deleteCascadeMatRepair(List<Integer> matRepairIds, Integer dataState) {

        //空值判断
        if (dataState == null) {
            throw new ParamsErrorException(HintMessage.DATASTATE_NULL);
        }
        if (matRepairIds == null) {
            throw new ParamsErrorException(HintMessage.LIST_NULL);
        }
        //记录异常信息
        String msg = "";
        switch (dataState) {
            case 1:
                msg = HintMessage.START_VALUE;
                break;
            case 2:
                msg = HintMessage.DELETE_VALUE;
                break;
            case 3:
                msg = HintMessage.STOP_VALUE;
                break;
            default:
                throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);
        }
        //执行删除操作
        int row = matRepairMapper.deleteMatRepair(matRepairIds, dataState);

        //根据传入的matRepairIds查询对应的工序和维修采集参数
        for (Integer matRepairId : matRepairIds) {

            //级联执行工序删除
            List<MatRepairFlow> matRepairFlowList = matRepairFlowMapper.queryMatRepairFlowByMatRepairId(matRepairId);
            if (matRepairFlowList != null && !matRepairFlowList.isEmpty()) {
                for (MatRepairFlow matRepairFlow : matRepairFlowList) {
                    matRepairFlowMapper.deleteMatRepairFlowByMatRepairFlowId(matRepairFlow.getMatRepairFlowId(), dataState);
                }
            }

            //级联执行维修采集参数删除
            List<MatRepairDete> matRepairDeteList = matRepairDeteMapper.queryMatRepairDeteByMatRepairId(matRepairId);
            if (matRepairDeteList != null && !matRepairDeteList.isEmpty()) {
                for (MatRepairDete matRepairDete : matRepairDeteList) {
                    matRepairDeteMapper.deleteMatRepairDeteByMatRepairDeteId(matRepairDete.getMatRepairDeteId(), dataState);
                }
            }

        }
        //声明msg字符串，用来存抛出的异常
        if (row == 0) {
            msg = msg + HintMessage.DEFEATED_VALUE;
        } else {
            msg = msg + HintMessage.SUCCESS_VALUE;
        }
        return JSONObject.oK(msg);

    }

    @Override
    public JSONObject saveMatRepairFlow(MatRepair matRepair) {
        try {
            //判空
            if (matRepair == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (matRepair.getMatRepairId() == null) {
                throw new ParamsErrorException(HintMessage.MATFLOWID_NULL);
            }
            //获取流程id
            Integer matRepairId = matRepair.getMatRepairId();
            //获取list集合
            List<MatRepairFlow> matRepairFlowList = new ArrayList<>();
            matRepairFlowList = matRepair.getMatRepairFlowList();
            for (MatRepairFlow matRepairFlow : matRepairFlowList) {
                matRepairFlow.setMatRepairId(matRepairId);
            }


            //获取数据库数据
            MatRepairFlow matRepairFlow1 = new MatRepairFlow();
            matRepairFlow1.setMatRepairId(matRepairId);
            List<MatRepairFlow> oldmatRepairFlowList = matRepairFlowMapper.queryMatRepairFlow(matRepairFlow1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldmatRepairFlowList != null) {
                for (MatRepairFlow matRepairFlow : oldmatRepairFlowList
                ) {
                    oldIds.add(matRepairFlow.getMatRepairFlowId());
                }
            }
            if (matRepairFlowList != null) {
                for (MatRepairFlow matRepairFlow : matRepairFlowList
                ) {
                    newIds.add(matRepairFlow.getMatRepairFlowId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = matRepairFlowMapper.deleteMatRepairFlow(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (matRepairFlowList != null) {
                for (MatRepairFlow matRepairFlow : matRepairFlowList
                ) {
                    if (matRepairFlow.getDataState() == null) {
                        matRepairFlow.setDataState(1);
                    }


                    if (matRepairFlow.getMatRepairFlowId() != null) {
                        if (matRepairFlow.getMatRepairFlowId().equals(0)) {
                            matRepairFlow.setMatRepairFlowId(null);

                            // 执行判重操作
                            Integer Counts = matRepairFlowMapper.checkMatRepairFlow(matRepairFlow);
                            if (Counts == 0) {
                                insertrow = insertrow + matRepairFlowMapper.insertMatRepairFlow(matRepairFlow);
                            }

                        } else {
                            // 执行判重操作
                            Integer Counts = matRepairFlowMapper.checkMatRepairFlow(matRepairFlow);
                            if (Counts == 0) {
                                updaterow = updaterow + matRepairFlowMapper.updateMatRepairFlow(matRepairFlow);
                            }
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    @Override
    public JSONObject saveMatRepairDete(MatRepair matRepair) {
        try {
            //判空
            if (matRepair == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (matRepair.getMatRepairId() == null) {
                throw new ParamsErrorException(HintMessage.MATREPAIRID_NULL);
            }
            if (matRepair.getRepairDetailId() == null) {
                throw new ParamsErrorException(HintMessage.REPAIRDETAILID_NULL);
            }


            //获取流程id
            Integer matRepairId = matRepair.getMatRepairId();
            Integer repairDetailId = matRepair.getRepairDetailId();
            //获取list集合
            List<MatRepairDete> matRepairDeteList = new ArrayList<>();
            matRepairDeteList = matRepair.getMatRepairDeteList();
            for (MatRepairDete matRepairDete : matRepairDeteList) {
                matRepairDete.setMatRepairId(matRepairId);
                matRepairDete.setRepairDetailId(repairDetailId);
            }


            //获取数据库数据
            MatRepairDete matRepairDete1 = new MatRepairDete();
            matRepairDete1.setMatRepairId(matRepairId);
            matRepairDete1.setRepairDetailId(repairDetailId);
            List<MatRepairDete> oldmatRepairDeteList = matRepairDeteMapper.queryMatRepairDete(matRepairDete1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldmatRepairDeteList != null) {
                for (MatRepairDete matRepairDete : oldmatRepairDeteList
                ) {
                    oldIds.add(matRepairDete.getMatRepairDeteId());
                }
            }
            if (matRepairDeteList != null) {
                for (MatRepairDete matRepairDete : matRepairDeteList
                ) {
                    newIds.add(matRepairDete.getMatRepairDeteId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = matRepairDeteMapper.deleteMatRepairDete(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (matRepairDeteList != null) {
                for (MatRepairDete matRepairDete : matRepairDeteList
                ) {
                    if (matRepairDete.getDataState() == null) {
                        matRepairDete.setDataState(1);
                    }


                    if (matRepairDete.getMatRepairDeteId() != null) {
                        if (matRepairDete.getMatRepairDeteId().equals(0)) {
                            matRepairDete.setMatRepairDeteId(null);

                            // 执行判重操作
                            Integer Counts = matRepairDeteMapper.checkMatRepairDete(matRepairDete);
                            if (Counts == 0) {
                                insertrow = insertrow + matRepairDeteMapper.insertMatRepairDete(matRepairDete);
                            }

                        } else {
                            // 执行判重操作
                            Integer Counts = matRepairDeteMapper.checkMatRepairDete(matRepairDete);
                            if (Counts == 0) {
                                updaterow = updaterow + matRepairDeteMapper.updateMatRepairDete(matRepairDete);
                            }
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 判重
     */
    public void checkParam(MatRepair matRepair) {

        //维修ID
        Integer repairId = matRepair.getRepairId();
        //物料版本ID
        Integer matVerId = matRepair.getMatVerId();

        //维修ID
        if (repairId == null) {
            throw new ParamsErrorException(HintMessage.REPAIRID_NULL);
        }
        //物料版本ID
        if (matVerId == null) {
            throw new ParamsErrorException(HintMessage.MATVERID_NULL);
        }

        // 执行判重操作
        Integer Counts = matRepairMapper.checkMatRepair(matRepair);
        if (Counts != 0) {
            throw new ParamsErrorException(HintMessage.REPEATING_DATA);
        }

    }

}
